﻿using System;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

namespace Web
{
    public partial class login : System.Web.UI.Page 
    {
        public void LockScreenAfterClick(WebControl wc, string message)
        {
            AddLockScreenScript();

            wc.Attributes.Add("onclick", String.Format("skm_LockScreen('{0}');", message.Replace("'", "\'")));
        }

        public void LockScreenAfterDDLChange(DropDownList ddl, string message)
        {
            AddLockScreenScript();

            ddl.Attributes.Add("onchange", String.Format("skm_LockScreen('{0}');", message.Replace("'", "\'")));
        }

        private void AddLockScreenScript()
        {
            if (ClientScript.IsClientScriptIncludeRegistered("skm_LockScreen")) return;

            // Add the JavaScript and <div> elements for freezing the screen

            // Register the JavaScript Include
            ClientScript.RegisterClientScriptInclude("skm_LockScreen",
                                                     Page.ResolveUrl("~/js/LockScreen.js?version=1.0"));

            //Add the <div> elements
            ClientScript.RegisterClientScriptBlock(GetType(), "skm_LockScreen_divs",
                                                   "<div id='skm_LockBackground' class='LockOff'></div><div id='skm_LockPane' class='LockOff'><div id='skm_LockPaneText'>&nbsp;</div></div>",
                                                   false);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            LockScreenAfterClick(btnEntrar, "Ingresando al sistema...");
            
            if (!IsPostBack)
                if (ExisteCookie)
                {
                    var errMessage = "";

                    ValidarIngreso(Request.Cookies["ToyotaTIPLogin"], ref errMessage);

                    if (!string.IsNullOrEmpty(errMessage))
                        PopUpMessage(errMessage);
                }

            txtUsuario.Text = NombreUsuario;
            txtUsuario.Focus();

        }

        protected string DomainName
        {
            get
            {
                return Request.ServerVariables["logon_user"].Split(Convert.ToChar(@"\")).Length == 2 ? Request.ServerVariables["logon_user"].Split(Convert.ToChar(@"\"))[0] : "";
            }
        }

        protected string DomainUser
        {
            get
            {
                return Request.ServerVariables["logon_user"].Split(Convert.ToChar(@"\")).Length == 2 ? Request.ServerVariables["logon_user"].Split(Convert.ToChar(@"\"))[1] : "";
            }
        }

        protected bool ExisteCookie
        {
            get
            {
                return (Request.Cookies["ToyotaTIPLogin"] != null);
            }
        }

        protected int UsuarioID
        {
            get { return Convert.ToInt32(Session["UserId"]); }
            set { Session["UserId"] = value; }
        }

        protected string NombreUsuario
        {
            get
            {
                var retorno = "";

                if (DomainUser != null)
                    retorno = DomainUser;

                if (txtUsuario.Text.Trim().Length > 0)
                    retorno = txtUsuario.Text.Trim();

                return retorno;
            }
            set { Session["NombreUsuario"] = value; }
        }

        protected string Clave
        {
            get
            {
                var retorno = "";

                if (txtClave.Text.Trim().Length > 0)
                    retorno = txtClave.Text.Trim();

                return retorno;
            }
        }

        protected int PerfilId
        {
            get { return (int)Session["PerfilId"]; }
            set { Session["PerfilId"] = value; }
        }

        protected void btnEntrar_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUsuario.Text) || string.IsNullOrEmpty(txtClave.Text)) return;

            var errMessage = "";

            ValidarIngreso(txtUsuario.Text.Trim(), txtClave.Text.Trim(), ref errMessage);

            if (!string.IsNullOrEmpty(errMessage))
                PopUpMessage(errMessage);
        }

        private void ValidarIngreso(HttpCookie cookie, ref string errMessage)
        {
            ValidarIngreso(cookie.Values["NombreUsuario"], cookie.Values["Clave"], ref errMessage);
        }

        private void ValidarIngreso(string nombreUsuario, string claveUsuario, ref string errMessage)
        {
            var usrTmp = new BLL.Usuarios();

            if (!usrTmp.CompararClave(nombreUsuario, Encrypt(claveUsuario), ref errMessage))
            {
                PopUpMessage("La clave del usuario es incorrecta o el usuario no existe");
                return;
            }

            UsuarioID = usrTmp.Usuario.UserId;
            NombreUsuario = usrTmp.Usuario.NombreCompleto;
            PerfilId = usrTmp.Usuario.PerfilId;

            if (chkRememberMe.Checked)
            {
                var cookie = new HttpCookie("ToyotaTIPLogin");
                cookie.Values.Add("UsuarioID", Encrypt(UsuarioID.ToString()));
                cookie.Values.Add("NombreUsuario", Encrypt(NombreUsuario));
                cookie.Values.Add("Clave", Encrypt(txtClave.Text.Trim()));
                cookie.Values.Add("PerfilId", Encrypt(PerfilId.ToString()));

                cookie.Expires = DateTime.Now.AddDays(365);
                Response.Cookies.Add(cookie);
            }

            Response.Redirect("~/Default.aspx");
        }

        protected void PopUpMessage(string message)
        {
            PopUpMessage(message, "Toyota - TIP", false);
        }

        protected void PopUpMessage(string message, string title)
        {
            PopUpMessage(message, title, false);
        }

        protected void PopUpMessage(string message, string title, bool persistent)
        {
            ClientScript.RegisterStartupScript(GetType(), "PopUpMessage", "<script>$(document).ready(function() { $.prompt('" + message + "', { title: \"" + title + "\", persistent: " + persistent.ToString().ToLower() + "}); });</script>");
        }

        public static string Encrypt(string valor)
        {
            if (valor == null) return null;

            try
            {
                byte[] encData_byte;
                encData_byte = Encoding.UTF8.GetBytes(valor);
                string encodedData = Convert.ToBase64String(encData_byte);

                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error Encrypt: " + ex.Message);
            }
        }

        public string Decrypt(string valorEncriptado)
        {
            if (valorEncriptado == null) return null;

            var encoder = new UTF8Encoding();
            Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(valorEncriptado);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            var decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            var result = new String(decoded_char);
            return result;
        }

    }
}